﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Threading;

namespace RadarMonitor.NetMonitor
{
    class NetMonitor
    {
        #region 单例
        private static readonly Lazy<NetMonitor>
            lazy =
            new Lazy<NetMonitor>
                (() => new NetMonitor());

        public static NetMonitor Instance { get { return lazy.Value; } }

        private NetMonitor()
        {

        }
        #endregion

        public string targetAddr { get; set; } = "10.78.135.200";

        // ping间隔（单位秒）
        public int QueryInterval { get; set; } = 1 * 60;

        public event Action<bool,string> PingResultEvent;

        private Timer loopTimer = null;

        internal void Start()
        {
            if (loopTimer != null)
                return;
            targetAddr = Setting.Setting.GetConfig().ping.IP;
            loopTimer = new Timer(CheckLoop, null, 0, QueryInterval * 1000);
        }

        internal void Stop()
        {
            loopTimer?.Dispose();
            loopTimer = null;

        }

        public void CheckLoop(object info)
        {
            bool online = false; //是否在线
            string description = null;
            Ping pingSender = new Ping();
            //调用同步 send 方法发送数据,将返回结果保存至PingReply实例
            try
            {
                PingReply reply = pingSender.Send(hostNameOrAddress: targetAddr, timeout: 500);

                if (reply.Status == IPStatus.Success)
                {
                    online = true;
                    StringBuilder sbuilder = new StringBuilder();
                    sbuilder.AppendLine(string.Format("答复的主机地址: {0} ", reply.Address.ToString()));
                    sbuilder.AppendLine(string.Format("往返时间: {0} ", reply.RoundtripTime));
                    sbuilder.AppendLine(string.Format("生存时间（TTL）: {0} ", reply.Options.Ttl));
                    description = sbuilder.ToString();
                }
                PingResultEvent?.Invoke(online, description);
            }
            catch
            {
                PingResultEvent?.Invoke(false, "网络访问失败");
            }
            

            

        }
    }
}
